import { Context } from 'koa';
import { LoginLog, User } from '@/models';
import * as response from '@/utils/response';
import { validate, commonSchemas } from '@/utils/validator';
import Joi from 'joi';
import { Op } from 'sequelize';

/**
 * 登录日志控制器
 */
export class LoginLogController {
  /**
   * 获取登录日志列表
   */
  async list(ctx: Context) {
    const schema = Joi.object({
      page: Joi.number().integer().min(1).default(1),
      pageSize: Joi.number().integer().min(1).max(100).default(20),
      username: Joi.string().optional(),
      status: Joi.string().valid('success', 'failed').optional(),
      ip: Joi.string().optional(),
      startTime: Joi.date().optional(),
      endTime: Joi.date().optional(),
    });

    const params = await validate<{
      page: number;
      pageSize: number;
      username?: string;
      status?: 'success' | 'failed';
      ip?: string;
      startTime?: Date;
      endTime?: Date;
    }>(ctx.query as any, schema);

    const where: any = {};

    // 构建查询条件
    if (params.username) {
      where.username = { [Op.like]: `%${params.username}%` };
    }

    if (params.status) {
      where.status = params.status;
    }

    if (params.ip) {
      where.ip = { [Op.like]: `%${params.ip}%` };
    }

    if (params.startTime || params.endTime) {
      where.loginTime = {};
      if (params.startTime) {
        where.loginTime[Op.gte] = params.startTime;
      }
      if (params.endTime) {
        where.loginTime[Op.lte] = params.endTime;
      }
    }

    const { count, rows } = await LoginLog.findAndCountAll({
      where,
      order: [['loginTime', 'DESC']],
      limit: params.pageSize,
      offset: (params.page - 1) * params.pageSize,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'firstName', 'lastName', 'email'],
          required: false,
        },
      ],
    });

    response.paginated(ctx, rows, count, params.page, params.pageSize);
  }

  /**
   * 获取登录日志详情
   */
  async getById(ctx: Context) {
    const schema = Joi.object({
      id: commonSchemas.uuid.required(),
    });

    const params = await validate<{ id: string }>(ctx.params, schema);

    const log = await LoginLog.findByPk(params.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'firstName', 'lastName', 'email'],
          required: false,
        },
      ],
    });

    if (!log) {
      return response.notFound(ctx, '登录日志不存在');
    }

    response.success(ctx, log);
  }

  /**
   * 获取登录统计
   */
  async getStats(ctx: Context) {
    const schema = Joi.object({
      days: Joi.number().integer().min(1).max(90).default(7),
    });

    const params = await validate<{ days: number }>(ctx.query as any, schema);

    const startDate = new Date();
    startDate.setDate(startDate.getDate() - params.days);

    // 获取总登录次数
    const totalLogins = await LoginLog.count({
      where: {
        loginTime: { [Op.gte]: startDate },
      },
    });

    // 获取成功登录次数
    const successLogins = await LoginLog.count({
      where: {
        loginTime: { [Op.gte]: startDate },
        status: 'success',
      },
    });

    // 获取失败登录次数
    const failedLogins = await LoginLog.count({
      where: {
        loginTime: { [Op.gte]: startDate },
        status: 'failed',
      },
    });

    // 获取独立用户数
    const uniqueUsers = await LoginLog.count({
      where: {
        loginTime: { [Op.gte]: startDate },
        status: 'success',
      },
      distinct: true,
      col: 'userId',
    });

    response.success(ctx, {
      totalLogins,
      successLogins,
      failedLogins,
      uniqueUsers,
      successRate: totalLogins > 0 ? ((successLogins / totalLogins) * 100).toFixed(2) : '0',
    });
  }
}

export default new LoginLogController();

